<template>
	<view class="">
		<!-- 弹出层 -->
		<uni-popup ref="popup" :mask-click="false" @maskClick="handleNaskClick()" :animation="false">
			<view class="popup_body">
				<view class="popup_top" @click="handleNaskClick()">
					<view class="popup_top_title">{{ title }}</view>
					<view class="popup_top_count" v-if="type === 'inventoryPlan'">
						<text>共{{ boxCount || 0 }}件有效</text><text>，{{ nSweptBoxCount || 0 }}件未扫</text>
					</view>
					<view class="popup_top_count" v-else>
						<text>共{{ materialList.length || 0 }}件</text></text>
					</view>
					<view class="popup_top_close" @click="close()">
						<i class="iconfont icon-shanchu"></i>
					</view>
				</view>
				<view class="popup_content" @click="handleNaskClick()">
					<uni-loading v-if="loading"></uni-loading>
					<!-- 扫描中 -->
					<view class="popup_content_scaning" v-else-if="isWaitScan">
						<template v-if="isContinuous">
							<textarea id="myTextarea"  ref="textareaRef" v-model="scanVal" :focus="isFocus" :adjust-position="false"
								@blur="isFocus=false" @input="onScanSuccess" placeholder="等待扫描中....."
								placeholder-class="popup_content_scaning_placeholder" maxlength="-1" />
							<!--  底部按钮  -->
							<view class="popup_content_btn">
								<button @click="changeScanningType(false)"
									class="popup_content_btn_item cancel margin_imp">扫码
								</button>
								<button @click="onContinuousScanSuccess()"
									class="popup_content_btn_item submit margin_imp" type="primary">完成
								</button>
							</view>
						</template>
						<template v-else>
							<input v-model="scanVal" :focus="isFocus" :adjust-position="false" @blur="isFocus=false"
								@confirm="onScanSuccess" placeholder="等待扫码中....."
								placeholder-class="popup_content_scaning_placeholder" />
							<view class="popup_content_btn">
								<button @click="changeScanningType(true)"
									class="popup_content_btn_item submit margin_imp">切换RFID扫描
								</button>
							</view>
						</template>
					</view>
					<!-- 扫描结果 -->
					<block v-else>
						<view class="popup_content_info">
							<scroll-view scroll-y="true" class="popup_content_info_scroll">
								<template v-for="item in materialList">
									<view class="material"
										:class="{materialSelect: isSelect && item.locationNo === barcodeTypeLocationNo}"
										@click="handleSelectBC(item.locationNo)">
										<view class="material_title">
											{{ item.materialName }}
										</view>
										<view class="material_row">
											<view class="material_row_item" v-if="item.materialNo">
												<view class="material_row_item_title">
													物料编码：
												</view>
												<view class="material_row_item_value">
													{{ item.materialNo }}
												</view>
											</view>
											<view class="material_row_item" v-if="item.materialNo">
												<view class="material_row_item_title">
													规格：
												</view>
												<view class="material_row_item_value">
													{{ item.materialSpec }}
												</view>
											</view>
										</view>
										<view class="material_row">
											<view class="material_row_item">
												<view class="material_row_item_title">
													批次：
												</view>
												<view class="material_row_item_value">
													{{ item.batchNo }}
												</view>
											</view>
										</view>
										<view class="material_row">
											<view class="material_row_item full_width">
												<view class="material_row_item_title">
													重量：
												</view>
												<view class="material_row_item_input">
													<input type="text"
														:disabled="(!isLocation || type === 'transfer') && item.barcodeType !== 'BC' && type !== 'taskRefund'"
														v-model="item.inputCount" placeholder="请输入物料重量"
														placeholder-class="placeholder_class" />
												</view>
											</view>
										</view>
									</view>
								</template>
							</scroll-view>
						</view>
						<!--  底部按钮  -->
						<view class="popup_content_btn">
							<button @click="close()" class="popup_content_btn_item cancel">取消</button>
							<button @click="reset()" class="popup_content_btn_item reset" type="warning">重新扫码</button>
							<button @click="submit()" class="popup_content_btn_item submit" type="primary">添加</button>
						</view>
					</block>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	import UniLoading from "../../vBase/components/uni-loading/uni-loading.vue"

	export default {
		components: {
			UniLoading
		},
		emits: ["scanSuccess", "success"],
		props: {
			title: {
				type: String,
				default: ""
			},
			type: {
				type: String,
				default: ""
			},
			isLocation: {
				type: Boolean,
				default: true
			},
			defaultStock: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				loading: false,
				isWaitScan: true,
				isFocus: false,
				scanVal: null,
				stockNo: null,
				locationNo: null,
				materialList: [],
				scanValList: [],
				isContinuous: false, // 是否为连续扫码
				billNo: null,
				taskBillNo: null,
				scanValLength: 0, // 已扫入的箱号数量
				boxCount: 0, // 有效箱数
				nSweptBoxCount: 0, // 未扫箱数
				noBatch: true,
				isSelect: false,
				barcodeTypeLocationNo: null,
			}
		},
		watch: {
			scanValLength() {
				this.getRfidCount()
			},
			isContinuous(val) {
				console.log(val)
				if (val) {
					this.$nextTick(() => {
						document.getElementById('myTextarea').addEventListener('mouseup', this.setCursorPosition);
					})
				} else {
					document.getElementById('myTextarea').removeEventListener('mouseup', this.setCursorPosition);
				}
			}
		},
		methods: {
			setCursorPosition(e) {
				const position = e.target.selectionStart
				if (position < e.target.value.length) {
					var myDiv = document.getElementById("myTextarea");
					var myTextAreas = myDiv.querySelectorAll("textarea");
					if (myTextAreas.length) {
						myTextAreas[0].selectionStart = e.target.value.length
						myTextAreas[0].selectionEnd = e.target.value.length
					}
				}
			},

			/**
			 * 打开面板
			 */
			open() {
				let self = this
				// 初始化参数
				this.reset()
				this.$refs.popup.open('bottom')
				// #ifdef APP-PLUS
				plus.key.addEventListener('keydown', event => {
					self.isFocus = true
				});
				// #endif
				// this.$nextTick(() => {
				// 	document.getElementById('myTextarea').addEventListener('mouseup', this.setCursorPosition);
				// })
			},

			/**
			 * 关闭面板
			 */
			close() {
				this.$refs.popup.close()
				this.isFocus = false
			},

			/**
			 * 重新扫码
			 */
			reset() {
				this.scanVal = null
				this.scanValLength = 0
				this.isWaitScan = true
				this.loading = false
				// this.isFocus = true
				this.materialList = []
				this.boxCount = 0 // 有效箱数
				this.nSweptBoxCount = 0 // 未扫箱数
				this.$nextTick(() => {
					this.isFocus = true
				})
			},

			/**
			 * 初始化扫码结果
			 * @param {Object} e
			 */
			initDataList(e) {
				let list = JSON.parse(e) ?? []
				if (list.length) {
					this.materialList = list.map(v => {
						return Object.assign(v, {
							isSale: true,
							inputCount: v.count
						})
					})
					this.isWaitScan = false
					this.loading = false
					this.scanVal = null
					this.scanValLength = 0
					this.isFocus = true
				} else {
					this.reset()
				}
			},

			/**
			 * 连续扫码完成
			 */
			async onContinuousScanSuccess() {
				let self = this
				if (!self.scanVal) {
					uni.showToast({
						title: "请扫描物料信息",
						icon: "none"
					})
					return
				}
				self.loading = true
				self.isFocus = false
				let rfidList = self.scanVal.split('\n')
				rfidList = rfidList.filter(item => {
					return item !== ""
				})
				this.$emit("scanSuccess", rfidList)
			},

			/**
			 * 监听扫码结果
			 * @param e
			 */
			async onScanSuccess(e) {
				let self = this
				if (self.isContinuous) {
					// 扫一个响一次
					this.handleMediaPlayer('success')
					if (this.scanVal) {
						setTimeout(() => {
							let rfidList = this.scanVal.split('\n')
							for (let i = rfidList.length - 1; i >= 0; i--) {
								if (!rfidList[i]) continue;
								if (rfidList.indexOf(rfidList[i]) < i) {
									rfidList.splice(i, 1)
								}
							}
							this.scanValLength = JSON.parse(JSON.stringify(rfidList)).length
							let newVal = rfidList.join("\n")
							this.scanVal = newVal
							this.loading = false
					
							this.reset()
						
						}, 10)
						
					}
				} else {
					
					if (self.loading) return
					setTimeout(()=>{
					
						self.loading = true
						self.$nextTick(() => {
							self.isFocus = true;
							// self.$refs.popup.focus();
						})
						
						self.$emit("scanSuccess", self.scanVal)
						self.loading = false
						self.scanVal = null
						self.scanValLength = 0
						this.$nextTick(() => {
							self.isFocus = true
						})
					},50)
					
				}
			},

			/** 立即入库*/
			async submit(close = true) {
				const {
					stockNo,
					locationNo,
					isLocation
				} = this;
				let materialListCopy = JSON.parse(JSON.stringify(this.materialList))
				if (!materialListCopy.length) {
					uni.showToast({
						title: `请添加物料`,
						icon: 'none'
					});
					return;
				}
				try {
					this.loading = true
					// 判断是否有输入的数过大和没有数据重量的
					let material = materialListCopy.find(item => {
						return !item.inputCount || item.inputCount <= 0 || (item.inputCount > item.count)
					})
					if (material) {
						let msg = !material.inputCount || material.inputCount <= 0 ?
							`请输入物料[${material.materialName}]重量` :
							`物料[${material.materialName}]重量不能超过 ${ material.count }`
						uni.showToast({
							title: msg,
							icon: 'none'
						});
						return;
					}
					this.$emit("success", materialListCopy)
				} finally {
					this.loading = false
					this.isFocus = true
				}
			},

			/**
			 * 查询有效rfid数量
			 */
			getRfidCount() {
				if (this.type !== 'inventoryPlan') return
				const self = this
				let currentList = self.scanVal.split('\n').filter(item => {
					return item !== ""
				})
				self.$api.getRfidCount({
					rfidList: currentList,
					billNo: self.billNo,
					locationNo: self.locationNo
				}).then(res => {
					if (res.res) {
						this.boxCount = res.boxCount
						this.nSweptBoxCount = res.nSweptBoxCount
					}
				})
			},

			/** 切换扫描方式 */
			changeScanningType(boo) {
				this.isContinuous = boo
				this.scanVal = null
				this.scanValLength = 0
				this.boxCount = 0
				this.nSweptBoxCount = 0
				this.reset()
			},

			/**
			 * @description 选择包材
			 * @param {Object} e
			 */
			handleSelectBC(e) {
				this.barcodeTypeLocationNo = e
			},

			/**
			 * 点击扫码框之外
			 */
			handleNaskClick() {
				this.isWaitScan = true
				this.loading = false
				this.$nextTick(() => {
					this.isFocus = true
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	@import "../../static/css/common";

	.popup_body {
		height: 80vh;
	}

	.margin_imp {
		margin: 10px 5px !important;
	}

	.materialSelect {
		box-shadow: 0 0 0 2px inset $primary !important;
	}
</style>
